package com.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.health.constant.MessageConstant;
import com.health.dao.CheckItemDao;
import com.health.entity.PageResult;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.CheckItem;
import com.health.service.CheckItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Classname CheckItemServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/15 13:44
 * @Author RainGrd
 */
@Service(interfaceClass = CheckItemService.class)
@Transactional
@Slf4j
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemDao checkItemDao;

    @Override
    public int saveCheckItem(CheckItem checkItem) {
        return checkItemDao.insertCheckItem(checkItem);
    }

    @Override
    public List<CheckItem> queryAll() {
        return checkItemDao.selectAll();
    }

    @Override
    public PageResult queryCheckItemPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<CheckItem> checkItemList = checkItemDao.selectByCondition(queryPageBean.getQueryString());
        log.info("查询出来的数据列表:{}", checkItemList);
        long count = checkItemDao.selectCountByCondition(queryPageBean.getQueryString());
        log.info("查询出来的总数:{}", count);
        return new PageResult(count, checkItemList);
    }

    @Override
    public Result clearCheckItem(Long id) {
        //不能直接删除，需要判断当前检查项是否和检查组关联，如果已经和检查组进行了关联则不允许删除
        long selectCheckItemById = checkItemDao.selectCheckItemById(id);
        if (selectCheckItemById > 0) {
            //当前检查项被引用，不能删除
            return Result.error("当前检查项被引用，不能删除");
        }
        try {
            int i = checkItemDao.deleteCheckItem(id);
            return i > 0 ? Result.success(MessageConstant.DELETE_CHECKGROUP_SUCCESS) : Result.error(MessageConstant.DELETE_CHECKGROUP_FAIL);
        } catch (Exception e) {
            return Result.error(MessageConstant.DELETE_CHECKGROUP_FAIL);
        }
    }

    @Override
    public Result editCheckItem(CheckItem checkItem) {

        try {
            long updateCheckItem = checkItemDao.updateCheckItem(checkItem);

            return updateCheckItem > 0 ? Result.success(MessageConstant.EDIT_CHECKITEM_SUCCESS) : Result.error(MessageConstant.EDIT_CHECKITEM_FAIL);
        } catch (Exception e) {
            return Result.error();
        }

    }
}
